package Heap;

import java.util.Arrays;

public class Heap {
    public int[] elem;
    public int usedSize;

    public Heap() {
        this.elem=new int[10];
    }

    public void init(int[] array) {
        for(int i=0;i<array.length;i++) {
            this.elem[i]=array[i];
            usedSize++;
        }
    }

//    构建大根堆
    public void createHeap() {
        int parent=(usedSize-1-1)/2;
        for(int i=parent;i>=0;i--) {
            siftDown(i,usedSize);
        }
    }

    public void siftDown(int parent,int end) {
        int child=2*parent+1;
        while(child<end) {
            if(child+1<end && elem[child+1]>elem[child]) {
                child++;
            }
            if(elem[child]> elem[parent]) {
                swap(child,parent);
                parent=child;
                child=2*parent+1;
            }else {
                break;
            }
        }
    }

    public void swap(int i,int j) {
        int temp=elem[i];
        elem[i]=elem[j];
        elem[j]=temp;
    }

//    向堆中插入一个元素

    public boolean isFull() {
        return usedSize==elem.length;
    }

    public void offer(int val) {
        if(isFull()) {
            this.elem= Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize++]=val;
        siftUp(usedSize-1);
    }

    public void siftUp(int child) {
        int parent=(child-1)/2;
        while(parent>=0) {
            if(elem[child]>elem[parent]) {
                swap(child,parent);
                child=parent;
                parent=(child-1)/2;
            }else {
                break;
            }
        }
    }

//    删除堆顶元素
    public boolean isEmpty() {
        return usedSize==0;
    }

    public void poll() {
        if(isEmpty()) return;
        swap(0,usedSize-1);
        usedSize--;
        siftDown(0, usedSize);
    }

//    堆排序
    public void heapSort() {
        int endIndex=usedSize-1;
        while(endIndex>0) {
            swap(0,endIndex);
            siftDown(0, endIndex);
            endIndex--;
        }
    }
}
